import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { Search, ArrowUpDown, User, Eye, Edit } from 'lucide-react';
import { Dialog, DialogContent, DialogTitle, Button, Input, Select, Switch, FormControlLabel } from '@mui/material';
import { useNavigate } from 'react-router-dom';
import logger from '../../utils/logger';

const Container = styled.div`
  width: 100%;
`;

const SearchBar = styled.div`
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
  align-items: center;
`;

const SearchInput = styled.input`
  flex: 1;
  max-width: 400px;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 14px;
  
  &:focus {
    outline: none;
    border-color: #3b82f6;
  }
`;

const FilterSelect = styled.select`
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 14px;
  background-color: white;
  cursor: pointer;
  
  &:focus {
    outline: none;
    border-color: #3b82f6;
  }
`;

const Table = styled.table`
  width: 100%;
  border-collapse: collapse;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
`;

const TableHeader = styled.th`
  background-color: #f9fafb;
  padding: 12px 16px;
  text-align: left;
  font-weight: 600;
  color: #374151;
  border-bottom: 1px solid #e5e7eb;
`;

const TableRow = styled.tr`
  &:hover {
    background-color: #f9fafb;
  }
`;

const TableCell = styled.td`
  padding: 12px 16px;
  border-bottom: 1px solid #e5e7eb;
  color: #111827;
`;

const StatusBadge = styled.span`
  display: inline-block;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  background-color: ${props => props.status === 'active' ? '#d1fae5' : '#fee2e2'};
  color: ${props => props.status === 'active' ? '#065f46' : '#991b1b'};
`;

const ActionButton = styled.button`
  padding: 4px 8px;
  margin-right: 8px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.2s;
  
  ${({ variant }) => {
    switch (variant) {
      case 'view':
        return 'background-color: #dbeafe; color: #1e40af;';
      case 'edit':
        return 'background-color: #fef3c7; color: #92400e;';
      default:
        return 'background-color: #f3f4f6; color: #374151;';
    }
  }}
  
  &:hover {
    ${({ variant }) => {
      switch (variant) {
        case 'view':
          return 'background-color: #bfdbfe;';
        case 'edit':
          return 'background-color: #fde68a;';
        default:
          return 'background-color: #e5e7eb;';
      }
    }}
  }
`;

const UserManagement = () => {
  // 状态声明
  const navigate = useNavigate();
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');
  const [sortField, setSortField] = useState('createdAt');
  const [sortDirection, setSortDirection] = useState('desc');
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(10);
  const [openEditDialog, setOpenEditDialog] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const [editingUser, setEditingUser] = useState({});
  
  // 计算过滤和排序后的用户数据
  const getFilteredUsers = () => {
    // 过滤用户
    let filtered = users.filter(user => {
      const matchesSearch = user.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
                           user.email.toLowerCase().includes(searchTerm.toLowerCase());
      
      const matchesFilter = filterStatus === 'all' ||
                           (filterStatus === 'active' && user.isActive) ||
                           (filterStatus === 'vip' && user.isVip) ||
                           (filterStatus === 'inactive' && !user.isActive);
      
      return matchesSearch && matchesFilter;
    });
    
    // 排序用户
    filtered.sort((a, b) => {
      if (a[sortField] < b[sortField]) return sortDirection === 'asc' ? -1 : 1;
      if (a[sortField] > b[sortField]) return sortDirection === 'asc' ? 1 : -1;
      return 0;
    });
    
    return filtered;
  };

  // 处理函数
  const handleSort = (field) => {
    if (sortField === field) {
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortDirection('asc');
    }
  };

  const paginate = (pageNumber) => setCurrentPage(pageNumber);
  const prevPage = () => setCurrentPage(prev => Math.max(prev - 1, 1));
  const nextPage = () => setCurrentPage(prev => Math.min(prev + 1, Math.ceil(getFilteredUsers().length / itemsPerPage)));
  
  const handleSaveEdit = () => {
    console.log('保存用户:', editingUser);
    setOpenEditDialog(false);
    logger.info('保存用户编辑', { userId: currentUser.id, updatedFields: Object.keys(editingUser) });
  };

  const handleToggleUserStatus = (userId) => {
    console.log('切换用户状态:', userId);
    // 实现切换用户状态的逻辑
  };

  const handleViewDetails = (user) => {
    navigate(`/admin/users/${user.id}`);
  };

  const handleEdit = (user) => {
    setCurrentUser(user);
    setEditingUser({ ...user });
    setOpenEditDialog(true);
    logger.info('编辑用户信息', { userId: user.id, username: user.username });
  };

  const formatDate = (dateString) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
  };

  // 获取用户数据
  useEffect(() => {
    // 记录进入用户管理页面
    logger.info('进入用户管理页面');
    const fetchUsers = async () => {
      try {
        // 模拟数据生成
        const mockUsers = Array.from({ length: 50 }, (_, index) => {
          // 先生成创建时间（0-30天前的随机时间）
          const daysSinceCreation = Math.floor(Math.random() * 30);
          const createdAt = new Date(Date.now() - daysSinceCreation * 24 * 60 * 60 * 1000);
          
          // 然后生成最后登录时间（在创建时间之后，但不超过当前时间）
          // 如果用户是今天创建的，最后登录时间就是今天
          // 否则，最后登录时间是创建时间之后到当前时间之间的随机时间
          let lastLogin;
          if (daysSinceCreation === 0) {
            // 用户是今天创建的，最后登录时间就是今天
            lastLogin = new Date();
          } else {
            // 用户是过去创建的，最后登录时间是创建时间之后到当前时间之间的随机时间
            // 计算创建时间到当前时间的毫秒数
            const creationTime = createdAt.getTime();
            const currentTime = Date.now();
            const timeRange = currentTime - creationTime;
            // 在这个时间范围内随机选择一个时间点
            lastLogin = new Date(creationTime + Math.floor(Math.random() * timeRange));
          }
          
          return {
            id: index + 1,
            username: `user${index + 1}`,
            email: `user${index + 1}@example.com`,
            createdAt: createdAt.toISOString(),
            isActive: Math.random() > 0.1,
            isVip: Math.random() > 0.8,
            lastLogin: lastLogin.toISOString(),
            analysesCount: Math.floor(Math.random() * 100)
          };
        });
        
        setTimeout(() => {
          setUsers(mockUsers);
          setLoading(false);
        }, 500);
      } catch (error) {
        console.error('获取用户列表失败:', error);
        logger.error('获取用户列表失败', { error: error.message });
        setLoading(false);
      }
    };

    fetchUsers();
  }, []);

  // 计算分页数据
  const filteredUsersResult = getFilteredUsers();
  const indexOfLastUser = currentPage * itemsPerPage;
  const indexOfFirstUser = indexOfLastUser - itemsPerPage;
  const currentUsers = filteredUsersResult.slice(indexOfFirstUser, indexOfLastUser);
  const totalPages = Math.ceil(filteredUsersResult.length / itemsPerPage);

  if (loading) {
    return <div>加载中...</div>;
  }

  return (
    <Container>
      <div style={{ marginBottom: '20px' }}>
        <h2 style={{ color: 'gray' }}>用户管理</h2>
      </div>

      <SearchBar>
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>
          <Search style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: '#94a3b8' }} size={18} />
          <SearchInput
            placeholder="搜索用户名或邮箱"
            value={searchTerm}
            onChange={(e) => {
              const term = e.target.value;
              setSearchTerm(term);
              if (term.length > 0) {
                logger.info('用户搜索操作', { searchTerm: term });
              }
            }}
          />
        </div>
        
        <FilterSelect
          value={filterStatus}
          onChange={(e) => setFilterStatus(e.target.value)}
        >
          <option value="all">所有状态</option>
          <option value="active">活跃</option>
          <option value="inactive">非活跃</option>
        </FilterSelect>
        
        <FilterSelect
          value="all"
          onChange={() => {}}
        >
          <option value="all">所有角色</option>
          <option value="admin">管理员</option>
          <option value="vip">VIP用户</option>
          <option value="regular">普通用户</option>
        </FilterSelect>
      </SearchBar>

      <Table>
        <thead>
          <tr>
            <TableHeader onClick={() => handleSort('username')}>
              用户名 <ArrowUpDown size={16} />
            </TableHeader>
            <TableHeader onClick={() => handleSort('email')}>
              邮箱 <ArrowUpDown size={16} />
            </TableHeader>
            <TableHeader>
              角色
            </TableHeader>
            <TableHeader onClick={() => handleSort('isActive')}>
              状态 <ArrowUpDown size={16} />
            </TableHeader>
            <TableHeader onClick={() => handleSort('analysesCount')}>
              分析次数 <ArrowUpDown size={16} />
            </TableHeader>
            <TableHeader onClick={() => handleSort('lastLogin')}>
              最后登录 <ArrowUpDown size={16} />
            </TableHeader>
            <TableHeader onClick={() => handleSort('createdAt')}>
              创建时间 <ArrowUpDown size={16} />
            </TableHeader>
            <TableHeader>操作</TableHeader>
          </tr>
        </thead>
        <tbody>
          {currentUsers.length > 0 ? (
            currentUsers.map(user => (
              <TableRow key={user.id}>
                <TableCell>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{ width: 32, height: 32, borderRadius: '50%', backgroundColor: '#e2e8f0', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#64748b' }}>
                      <User size={16} />
                    </div>
                    <span style={{ fontWeight: 500 }}>{user.username}</span>
                  </div>
                </TableCell>
                <TableCell>{user.email}</TableCell>
                <TableCell>
                  <span style={{ 
                      display: 'inline-block',
                      padding: '4px 8px',
                      borderRadius: '12px',
                      fontSize: '12px',
                      fontWeight: '500',
                      backgroundColor: user.isVip ? '#f59e0b' : '#6b7280',
                      color: 'white'
                    }}>
                    {user.isVip ? 'VIP' : '普通'}
                  </span>
                </TableCell>
                <TableCell>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <StatusBadge status={user.isActive ? 'active' : 'inactive'}>
                      {user.isActive ? '活跃' : '禁用'}
                    </StatusBadge>
                    <Switch
                      checked={user.isActive}
                      onChange={() => handleToggleUserStatus(user.id)}
                      size="small"
                    />
                  </div>
                </TableCell>
                <TableCell>{user.analysesCount || 0}</TableCell>
                <TableCell>{formatDate(user.lastLogin)}</TableCell>
                <TableCell>{formatDate(user.createdAt)}</TableCell>
                <TableCell>
                  <div style={{ display: 'flex', gap: 4 }}>
                    <ActionButton onClick={() => handleViewDetails(user)} title="查看详情" variant="view">
                      <Eye size={16} />
                    </ActionButton>
                    <ActionButton onClick={() => handleEdit(user)} title="编辑" variant="edit">
                      <Edit size={16} />
                    </ActionButton>
                  </div>
                </TableCell>
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={8} style={{ textAlign: 'center', padding: '40px', color: '#64748b' }}>
                没有找到匹配的用户
              </TableCell>
            </TableRow>
          )}
        </tbody>
      </Table>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '20px' }}>
        <span style={{ marginRight: '16px', alignSelf: 'center' }}>
          显示 {indexOfFirstUser + 1} 到 {Math.min(indexOfLastUser, filteredUsersResult.length)} 条，共 {filteredUsersResult.length} 条记录
        </span>
        <div>
          <button
            onClick={prevPage}
            disabled={currentPage === 1}
            style={{
              padding: '8px 12px',
              border: '1px solid #d1d5db',
              backgroundColor: 'white',
              borderRadius: '4px',
              cursor: currentPage === 1 ? 'not-allowed' : 'pointer',
              opacity: currentPage === 1 ? 0.5 : 1,
              marginRight: '8px'
            }}
          >
            上一页
          </button>
          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            let pageNum;
            if (totalPages <= 5) {
              pageNum = i + 1;
            } else if (currentPage <= 3) {
              pageNum = i + 1;
            } else if (currentPage >= totalPages - 2) {
              pageNum = totalPages - 4 + i;
            } else {
              pageNum = currentPage - 2 + i;
            }
            
            return (
              <button
                key={pageNum}
                onClick={() => paginate(pageNum)}
                style={{
                  padding: '8px 12px',
                  border: '1px solid #d1d5db',
                  backgroundColor: pageNum === currentPage ? '#3b82f6' : 'white',
                  color: pageNum === currentPage ? 'white' : '#374151',
                  borderRadius: '4px',
                  cursor: 'pointer',
                  marginRight: '8px'
                }}
              >
                {pageNum}
              </button>
            );
          })}
          <button
            onClick={nextPage}
            disabled={currentPage === totalPages}
            style={{
              padding: '8px 12px',
              border: '1px solid #d1d5db',
              backgroundColor: 'white',
              borderRadius: '4px',
              cursor: currentPage === totalPages ? 'not-allowed' : 'pointer',
              opacity: currentPage === totalPages ? 0.5 : 1
            }}
          >
            下一页
          </button>
        </div>
      </div>

      {/* 编辑用户对话框 */}
      <Dialog open={openEditDialog} onClose={() => setOpenEditDialog(false)}>
        <DialogTitle>编辑用户</DialogTitle>
        <DialogContent>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16, marginTop: 8 }}>
            <div>
              <label htmlFor="username" style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>用户名</label>
              <Input
                id="username"
                fullWidth
                value={editingUser.username || ''}
                onChange={(e) => setEditingUser({ ...editingUser, username: e.target.value })}
                disabled
              />
            </div>
            
            <div>
              <label htmlFor="email" style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>邮箱</label>
              <Input
                id="email"
                fullWidth
                type="email"
                value={editingUser.email || ''}
                onChange={(e) => setEditingUser({ ...editingUser, email: e.target.value })}
              />
            </div>
            
            <FormControlLabel
              control={
                <Switch
                  id="active"
                  checked={editingUser.isActive || false}
                  onChange={(e) => setEditingUser({ ...editingUser, isActive: e.target.checked })}
                />
              }
              label="启用用户"
            />
          </div>
        </DialogContent>
        <div style={{ padding: '16px', display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
          <Button onClick={() => setOpenEditDialog(false)}>取消</Button>
          <Button onClick={handleSaveEdit} color="primary" variant="contained">保存</Button>
        </div>
      </Dialog>
    </Container>
  );
};

export default UserManagement;